package yiran.stock.lang;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.stock.Stock;
import yiran.stock.output.Logger;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.MissingFormatArgumentException;

public class LangHelper {
    private static FileConfiguration langConfig;
    private static Stock plugin;

    public static void init(Stock plugin) {
        LangHelper.plugin = plugin;
        reload();
    }

    public static void reload() {
        if (plugin == null || plugin.getDataFolder() == null) {
            Logger.error("LangHelper 未初始化或 dataFolder 为空");
            return;
        }

        try {
            String langFile = plugin.getConfig().getString("language", "zh_CN") + ".yml";
            File file = new File(plugin.getDataFolder(), "lang/" + langFile);

            if (!file.exists()) {
                plugin.saveResource("lang/" + langFile, false);
            }

            langConfig = YamlConfiguration.loadConfiguration(file);
        } catch (Exception e) {
            Logger.error("语言文件加载失败: " + e.getMessage());
        }
    }

    public static String getString(String path, Object... args) {
        if (langConfig == null) return "LANG_CONFIG_NULL";

        String message = langConfig.getString(path);
        if (message == null) {
            return "MISSING_KEY: " + path;
        }
        return String.format(message, args);
    }

    public static List<String> getStringList(String path) {
        if (langConfig == null) return Collections.singletonList("LANG_CONFIG_NULL");

        List<String> messages = langConfig.getStringList(path);
        if (messages == null || messages.isEmpty()) {
            return Collections.singletonList("MISSING_KEY: " + path);
        }
        return messages;
    }

    public static String getSafeString(String key, Object... args) {
        if (langConfig == null) return "LANG_CONFIG_NULL";

        String message = langConfig.getString(key);
        if (message == null) {
            return "MISSING_KEY: " + key;
        }

        // 计算预期参数数量
        long expectedArgs = message.chars().filter(ch -> ch == '%').count();

        if (expectedArgs != args.length) {
            Logger.warn("参数数量不匹配: " + key + " 预期 " + expectedArgs + " 实际 " + args.length);
        }

        try {
            return String.format(message, args);
        } catch (Exception e) {
            Logger.error("格式化错误: " + key + " - " + e.getMessage());
            return message + " (格式化失败)";
        }
    }
}

